package com.liang.maogouyuyin.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import com.liang.maogouyuyin.TheBaseApplication
import com.liang.maogouyuyin.databinding.FragmentVarietyBinding
import com.liang.maogouyuyin.ui.adapter.VarietyAdapter
import com.liang.maogouyuyin.ui.viewmodel.PetMenuViewModel

class VarietyFragment: Fragment() {
    private lateinit var binding: FragmentVarietyBinding

    private lateinit var adapter: VarietyAdapter

    private lateinit var petMenuViewModel: PetMenuViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentVarietyBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initData()
        initView()
        initClick()
        updateUI()
    }

    private fun initData() {
        petMenuViewModel = TheBaseApplication.getInstance().petMenuViewModel
        petMenuViewModel.getCatVariety()
        petMenuViewModel.getDogVariety()
    }

    private fun initView() {
        binding.varietyRecyclerview.layoutManager = GridLayoutManager(requireContext(), 3)
        adapter = VarietyAdapter(requireContext())
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initClick() {
        binding.varietyRadioCat.setOnClickListener {
            adapter.setList(petMenuViewModel.catVarietyList.value!!)
            adapter.notifyDataSetChanged()
        }

        binding.varietyRadioDog.setOnClickListener {
            adapter.setList(petMenuViewModel.dogVarietyList.value!!)
            adapter.notifyDataSetChanged()
        }
    }

    private fun updateUI() {
        petMenuViewModel.catVarietyList.observe(viewLifecycleOwner) {
            adapter.setList(it)
            binding.varietyRecyclerview.adapter = adapter
        }
    }
}